from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from .models import *
from main.models import *
from django.contrib.auth.views import auth_login, auth_logout, login_required
# Create your views here.


@login_required(login_url="/user/login",)
def collect(request):
    ct = Collect.objects.filter(user=request.user)
    return render(request, "operate/collect.html", context={"ct": ct})


def change_collect(request):
    if request.method == "POST":
        book_id = request.POST.get("book_id")
        book = Book.objects.get(id=book_id)
        c = Collect.objects.filter(user=request.user, book=book).first()
        if c:
            c.delete()
            return JsonResponse({
                "code": 0,
                "msg": "已取消收藏",
                "data": {
                    "state": False
                }
            })
        else:
            temp = Collect()
            temp.user = request.user
            temp.book = book
            temp.save()
            return JsonResponse({
                "code": 0,
                "msg": "收藏成功",
                "data": {
                    "state": True
                }
            })
    else:
        return JsonResponse({
            "code": -1,
            "msg": "请求方式无效"
        })


